package com.brother.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.brother.database.DataBase;
import com.brother.model.InterestPoint;
import com.brother.model.Tracker;

public class InterestPointService extends BaseService{
	private Logger log = Logger.getLogger(InterestPointService.class);
	
	/**
	 * @param userId
	 * @return
	 */
	public List<InterestPoint> findInterestPointByUser(String userId){
		String sql = "select * from interestPoint where userId="+userId;
		List<InterestPoint> result = new ArrayList<InterestPoint>();
		try {
			log.debug(sql);
			ResultSet rs = DataBase.query(sql);	
			while(rs.next()){
				InterestPoint p = new InterestPoint();
				this.setModel(p,rs);
				result.add(p);
			}
		} catch (Exception e) {
			log.error("", e);
		}finally{
			DataBase.closeConnection();
		}
		return result;
	}
	
	public void addOrUpdate(String id, String userId, float lat, float lng, String text){
		String sql = "select * from interestPoint where pid='"+id+"'";
		try {
			ResultSet rs = DataBase.query(sql);	
			if(rs.next()){ // 已经有记录，需要更新
				sql = "update interestPoint set lat="+lat+",lng="+lng+",text='"+this.escapeDBField(text)
				+"' where pid='"+id+"'";
				log.debug(sql);
				DataBase.update(sql);
			}else{
				sql = "insert into interestPoint(pid,userId,lat,lng,text) values('"+id+"',"+userId+","
				+lat+","+lng+",'"+this.escapeDBField(text)+"')";
				log.debug(sql);
				DataBase.update(sql);
			}
		} catch (Exception e) {
			log.error("", e);
		}finally{
			DataBase.closeConnection();
		}
	}
	
	public void delete(String id){
		String sql = "delete from interestPoint where pid='"+id+"'";
		try {
			DataBase.update(sql);	
		} catch (Exception e) {
			log.error("", e);
		}finally{
			DataBase.closeConnection();
		}
	}
	
	private void setModel(InterestPoint t, ResultSet rs) throws SQLException {
		t.setId(rs.getString("pid"));
		t.setLat(rs.getFloat("lat"));
		t.setLng(rs.getFloat("lng"));
		t.setUserId(rs.getInt("userid"));
		t.setText(rs.getString("text"));
	}
}
